const Router = require("koa-router");
const Sequelize = require("sequelize");

const { Raffle_record, Raffle } = require("@models/raffle");

const { Address } = require("@models/address");
const { User } = require("@models/user");
const { Auth } = require("@middlewares/auth");

const { redis } = require("@core/redis");
const axios = require("axios");
const { Order } = require("@models/order");

const { Op } = require("sequelize");

const router = new Router({
  prefix: "/admin/raffle",
});

// 获取奖品列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const { count: total, rows } = await Raffle.findAndCountAll({
    limit: pageSize, // 每页数量
    offset, // 偏移量
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 奖品发货
router.post("/send_out_goods", new Auth().m, async (ctx, next) => {
  const { tracking_number, raffle_record_id } = ctx.request.body;
  const raffle = await Raffle_record.update(
    { tracking_number },
    {
      where: {
        raffle_record_id,
      },
    }
  );

  if (raffle[0] == 0) {
    throw new global.errs.AuthFailed("添加失败");
  }
  ctx.body = {
    code: 200,
    msg: "发货成功",
  };
});

// 获取中奖名单
router.post("/win/list", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10, phone = "" } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const { count: total, rows } = await Raffle_record.findAndCountAll({
    where: {},
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]], // 排序
    include: [
      {
        model: Raffle,
        required: false,
      },
      {
        model: User,
        where: { phone: { [Op.like]: `%${phone}%` } },
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 添加奖品
router.post("/add", new Auth().m, async (ctx, next) => {
  const { ...res } = ctx.request.body;
  await Raffle.verify(null, res.probability);
  const raffle = await Raffle.create(res);
  if (!raffle) {
    throw new global.errs.AuthFailed("添加失败");
  }
  ctx.body = {
    code: 200,
    msg: "添加成功",
  };
});

// 修改奖品
router.post("/update", new Auth().m, async (ctx, next) => {
  const { raffle_id, ...res } = ctx.request.body;

  // 验证奖品概率
  await Raffle.verify(raffle_id, res.probability);

  const raffle = await Raffle.update(res, {
    where: {
      raffle_id,
    },
  });

  if (raffle[0] == 0) {
    throw new global.errs.AuthFailed("更新失败");
  }
  ctx.body = {
    code: 200,
    msg: "修改成功",
  };
});

// 删除奖品
router.post("/delete", new Auth().m, async (ctx, next) => {
  const { raffle_id } = ctx.request.body;

  const raffle = await Raffle.destroy({
    where: {
      raffle_id,
    },
    force: true,
  });

  if (!raffle) {
    throw new global.errs.AuthFailed("删除失败");
  }

  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

// 抽奖消耗积分
router.post("/point", new Auth().m, async (ctx, next) => {
  const { point } = ctx.request.body;

  const raffle = await Raffle.update({ point }, { where: {} });

  if (raffle[0] == 0) {
    throw new global.errs.AuthFailed("积分修改失败");
  }
  ctx.body = {
    code: 200,
    msg: "积分修改成功",
  };
});

// 查询物流
router.post("/logistics", async (ctx, next) => {
  const { tracking_number, mobile } = ctx.request.body;
  // 设置你的AppCode，从阿里云获取

  let result;
  const res = await redis.get(tracking_number);
  if (!res) {
    // 查询物流
    try {
      result = await axios.get(global.config.wuliu.url, {
        params: {
          number: tracking_number,
          mobile,
        },
        headers: {
          Authorization: `APPCODE ${global.config.wuliu.appCode}`,
        },
      });
    } catch (e) {
      throw new global.errs.AuthFailed("查询失败");
    }

    result = result.data.data;
    // 缓存
    if (result.logisticsStatus == "SIGN") {
      redis.set(
        tracking_number,
        JSON.stringify(result),
        "EX",
        60 * 60 * 24 * 30 * 12 // 缓存12个月
      );
    } else {
      redis.set(tracking_number, JSON.stringify(result), "EX", 60 * 60 * 6);
    }
    
  } else {
    result = JSON.parse(res);
  }

  await Order.update(
    { order_status: result.state == 3 ? 2 : 1 },
    { where: { tracking_number } }
  );

  ctx.body = {
    code: 200,
    msg: "查询成功",
    data: result,
  };
});

module.exports = router;
